/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package Transaction;


import Modelo.Numero_a_Letra;
import Modelo.Conection;
import Modelo.Functions;
import static Transaction.Venta.tbl_venta;
import java.sql.SQLException;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.JOptionPane;
import javax.swing.table.DefaultTableModel;

/**
 *
 * @author Rudy
 */
public class AddProduct extends javax.swing.JDialog {

    /**
     * Creates new form AddProduct
     */
    DefaultTableModel modelo;
    Conection conection;
    Numero_a_Letra NumLetra = new Numero_a_Letra();
    
    public AddProduct(java.awt.Frame parent, boolean modal,Conection pconection) {
        super(parent, modal);
        initComponents();
        this.setLocationRelativeTo(null);
        conection=pconection;
        conection.Conectar();
        modelo = (DefaultTableModel)tbl_producto.getModel();
        try {
            modelo=conection.cargarTablaProducto(modelo," ORDER BY id_producto ");
        } catch (SQLException ex) {
            Logger.getLogger(AddProduct.class.getName()).log(Level.SEVERE, null, ex);
        }
    }

    /**
     * This method is called from within the constructor to initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is always
     * regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        jPanel1 = new javax.swing.JPanel();
        jScrollPane2 = new javax.swing.JScrollPane();
        tbl_producto = new javax.swing.JTable();
        btn_addproduct = new javax.swing.JButton();
        jLabel1 = new javax.swing.JLabel();
        tf_search = new javax.swing.JTextField();
        cb_search_product = new javax.swing.JComboBox();
        btn_exit = new javax.swing.JButton();

        setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE);
        setTitle("Producto");

        jPanel1.setBorder(javax.swing.BorderFactory.createEtchedBorder());

        tbl_producto.setModel(new javax.swing.table.DefaultTableModel(
            new Object [][] {

            },
            new String [] {
                "Nro", "*", "Codigo", "Denominacion", "P.U", "Descuento", "Ganancia", "Stock"
            }
        ) {
            Class[] types = new Class [] {
                java.lang.Object.class, java.lang.Boolean.class, java.lang.Object.class, java.lang.Object.class, java.lang.Object.class, java.lang.Object.class, java.lang.Object.class, java.lang.Object.class
            };
            boolean[] canEdit = new boolean [] {
                false, true, false, false, false, false, false, false
            };

            public Class getColumnClass(int columnIndex) {
                return types [columnIndex];
            }

            public boolean isCellEditable(int rowIndex, int columnIndex) {
                return canEdit [columnIndex];
            }
        });
        jScrollPane2.setViewportView(tbl_producto);
        tbl_producto.getColumnModel().getColumn(0).setMinWidth(80);
        tbl_producto.getColumnModel().getColumn(0).setPreferredWidth(80);
        tbl_producto.getColumnModel().getColumn(0).setMaxWidth(80);
        tbl_producto.getColumnModel().getColumn(1).setMinWidth(50);
        tbl_producto.getColumnModel().getColumn(1).setPreferredWidth(50);
        tbl_producto.getColumnModel().getColumn(1).setMaxWidth(50);
        tbl_producto.getColumnModel().getColumn(2).setMinWidth(90);
        tbl_producto.getColumnModel().getColumn(2).setPreferredWidth(90);
        tbl_producto.getColumnModel().getColumn(2).setMaxWidth(90);
        tbl_producto.getColumnModel().getColumn(4).setMinWidth(80);
        tbl_producto.getColumnModel().getColumn(4).setPreferredWidth(80);
        tbl_producto.getColumnModel().getColumn(4).setMaxWidth(80);
        tbl_producto.getColumnModel().getColumn(5).setMinWidth(80);
        tbl_producto.getColumnModel().getColumn(5).setPreferredWidth(80);
        tbl_producto.getColumnModel().getColumn(5).setMaxWidth(80);
        tbl_producto.getColumnModel().getColumn(6).setMinWidth(80);
        tbl_producto.getColumnModel().getColumn(6).setPreferredWidth(80);
        tbl_producto.getColumnModel().getColumn(6).setMaxWidth(80);
        tbl_producto.getColumnModel().getColumn(7).setMinWidth(60);
        tbl_producto.getColumnModel().getColumn(7).setPreferredWidth(60);
        tbl_producto.getColumnModel().getColumn(7).setMaxWidth(60);

        btn_addproduct.setText("Agregar");
        btn_addproduct.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btn_addproductActionPerformed(evt);
            }
        });

        jLabel1.setText("Buscar Por :");

        tf_search.addKeyListener(new java.awt.event.KeyAdapter() {
            public void keyReleased(java.awt.event.KeyEvent evt) {
                tf_searchKeyReleased(evt);
            }
        });

        cb_search_product.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "Codigo", "Nombre" }));

        btn_exit.setText("Cancelar");
        btn_exit.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btn_exitActionPerformed(evt);
            }
        });

        javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout(jPanel1);
        jPanel1.setLayout(jPanel1Layout);
        jPanel1Layout.setHorizontalGroup(
            jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel1Layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(jScrollPane2)
                    .addGroup(jPanel1Layout.createSequentialGroup()
                        .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addGroup(jPanel1Layout.createSequentialGroup()
                                .addComponent(btn_addproduct, javax.swing.GroupLayout.PREFERRED_SIZE, 100, javax.swing.GroupLayout.PREFERRED_SIZE)
                                .addGap(18, 18, 18)
                                .addComponent(btn_exit, javax.swing.GroupLayout.PREFERRED_SIZE, 89, javax.swing.GroupLayout.PREFERRED_SIZE))
                            .addGroup(jPanel1Layout.createSequentialGroup()
                                .addGap(34, 34, 34)
                                .addComponent(jLabel1)
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                                .addComponent(cb_search_product, javax.swing.GroupLayout.PREFERRED_SIZE, 189, javax.swing.GroupLayout.PREFERRED_SIZE)
                                .addGap(18, 18, 18)
                                .addComponent(tf_search, javax.swing.GroupLayout.PREFERRED_SIZE, 277, javax.swing.GroupLayout.PREFERRED_SIZE)))
                        .addGap(0, 443, Short.MAX_VALUE)))
                .addContainerGap())
        );
        jPanel1Layout.setVerticalGroup(
            jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel1Layout.createSequentialGroup()
                .addGap(21, 21, 21)
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel1)
                    .addComponent(tf_search, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(cb_search_product, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(btn_addproduct)
                    .addComponent(btn_exit))
                .addGap(11, 11, 11)
                .addComponent(jScrollPane2, javax.swing.GroupLayout.DEFAULT_SIZE, 482, Short.MAX_VALUE)
                .addContainerGap())
        );

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(jPanel1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                .addContainerGap())
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(jPanel1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                .addContainerGap())
        );

        pack();
    }// </editor-fold>//GEN-END:initComponents

    private void tf_searchKeyReleased(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_tf_searchKeyReleased
        if(tf_search.getText().equals(""))
        {
            try {
                modelo=conection.cargarTablaProducto(modelo,"");
            } catch (SQLException ex) {
                Logger.getLogger(AddProduct.class.getName()).log(Level.SEVERE, null, ex);
            }
        }
        else
        {
            try {
                switch(cb_search_product.getSelectedItem().toString())
                {
                    case "Codigo":
                        modelo=conection.cargarTablaProducto(modelo," WHERE id_producto like '%"+tf_search.getText()+"%' ORDER BY id_producto");
                        break;
                    case "Nombre":
                        modelo=conection.cargarTablaProducto(modelo," WHERE nombre like '%"+tf_search.getText()+"%' ORDER BY nombre");
                        break;
                }       
            } catch (SQLException ex) {
                Logger.getLogger(AddProduct.class.getName()).log(Level.SEVERE, null, ex);
            }
            
        }   
    }//GEN-LAST:event_tf_searchKeyReleased

    private void btn_addproductActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btn_addproductActionPerformed
        // TODO add your handling code here        
        //verificar productos iguales
        boolean error=false;
        String cod_error="";
        String denom_error="";
        for (int i = 0; i < tbl_producto.getRowCount(); i++) {
            if(tbl_producto.getValueAt(i, 1)==true)
            {
                for(int j = 0; j < Venta.tbl_venta.getRowCount(); j++){
                    if(tbl_producto.getValueAt(i, 2).equals(tbl_venta.getValueAt(j, 1))){
                        error=true;                    
                        cod_error=tbl_producto.getValueAt(i, 2).toString();
                        denom_error=tbl_producto.getValueAt(i, 3).toString();
                        j=tbl_venta.getRowCount();
                        i=tbl_producto.getRowCount();
                    }                    
               }
            }
        }        
        if(!error)
        {
            //agregar producto
            for (int i = 0; i < tbl_producto.getRowCount(); i++) {
                if(tbl_producto.getValueAt(i, 1)==true)
                {
                        double pu=Double.valueOf(tbl_producto.getValueAt(i, 4).toString());
                        double dcto=Double.valueOf(tbl_producto.getValueAt(i, 5).toString());
                        Object D[] ={Venta.tbl_venta.getRowCount()+1,tbl_producto.getValueAt(i, 2),tbl_producto.getValueAt(i, 3),1,pu,1*pu,dcto,Functions.round(1*pu+(1*pu)*(dcto/100),2),tbl_producto.getValueAt(i, 7)};
                        Venta.getModelo().addRow(D);               
                }            
            } 
            //calcular totales
            int fila = Venta.getModelo().getRowCount();
            double precio_venta=0;
            double valor_bruto=0;
            double descuento=0;
            double valor_neto=0;
            double recargos=0;
            double valor_venta=0;
            double igv=0;
            for (int i = 0; i < fila; i++) {
                double vb=0;
                double dcto=0;
                if(!((Venta.getModelo().getValueAt(i, 1).toString().split("-"))[0]).equals("ST"))
                {
                    vb=Integer.parseInt(Venta.getModelo().getValueAt(i, 3).toString())*Double.parseDouble(Venta.getModelo().getValueAt(i, 4).toString());
                    dcto=vb*(Double.parseDouble(Venta.getModelo().getValueAt(i, 6).toString())/100);
                    Venta.getModelo().setValueAt(vb, i, 5);
                    Venta.getModelo().setValueAt(Functions.round(vb-dcto,2), i, 7);
                }
                Venta.getModelo().setValueAt(i+1, i, 0);
                valor_bruto+=vb;
                descuento+=dcto;
                valor_neto+=vb-dcto;
                recargos+=0;
                valor_venta+=vb-dcto;            
                //precio_venta += (Double.parseDouble(modelo.getValueAt(i, 7).toString()));
            }
            igv=valor_venta*0.18;
            precio_venta=valor_venta+igv;
            
            Venta.lbl_precio_venta.setText(String.valueOf(Functions.round(precio_venta,2)));
            Venta.lbl_valor_bruto.setText(String.valueOf(Functions.round(valor_bruto,2)));
            Venta.lbl_descuento.setText(String.valueOf(Functions.round(descuento,2)));
            Venta.lbl_valor_neto.setText(String.valueOf(Functions.round(valor_neto,2)));
            Venta.lbl_recargos.setText(String.valueOf(Functions.round(recargos,2)));
            Venta.lbl_valor_venta.setText(String.valueOf(Functions.round(valor_venta,2)));
            Venta.lbl_igv.setText(String.valueOf(Functions.round(igv,2)));
            Venta.lbl_num_letra_en.setText(NumLetra.Convertir(String.valueOf(Functions.round(precio_venta,2)),true));
            this.setVisible(false);
        }
        else{
           JOptionPane.showMessageDialog(this,"Codigo: "+cod_error+"\n "+denom_error+"\n ya existe en la lista, \nSolo edite la cantidad en la tabla.", "ATENCION", JOptionPane.INFORMATION_MESSAGE);

        }
    }//GEN-LAST:event_btn_addproductActionPerformed

    private void btn_exitActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btn_exitActionPerformed
        // TODO add your handling code here:
        this.setVisible(false);
    }//GEN-LAST:event_btn_exitActionPerformed

    /**
     * @param args the command line arguments
     */
    public static void main(String args[]) {
        /* Set the Nimbus look and feel */
        //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
        /* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.
         * For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html 
         */
        try {
            for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
                if ("Nimbus".equals(info.getName())) {
                    javax.swing.UIManager.setLookAndFeel(info.getClassName());
                    break;
                }
            }
        } catch (ClassNotFoundException ex) {
            java.util.logging.Logger.getLogger(AddProduct.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (InstantiationException ex) {
            java.util.logging.Logger.getLogger(AddProduct.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (IllegalAccessException ex) {
            java.util.logging.Logger.getLogger(AddProduct.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (javax.swing.UnsupportedLookAndFeelException ex) {
            java.util.logging.Logger.getLogger(AddProduct.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        }
        //</editor-fold>

        /* Create and display the dialog */
        java.awt.EventQueue.invokeLater(new Runnable() {
            public void run() {
                AddProduct dialog = new AddProduct(new javax.swing.JFrame(), true, null);
                dialog.addWindowListener(new java.awt.event.WindowAdapter() {
                    @Override
                    public void windowClosing(java.awt.event.WindowEvent e) {
                        System.exit(0);
                    }
                });
                dialog.setVisible(true);
            }
        });
    }
    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton btn_addproduct;
    private javax.swing.JButton btn_exit;
    private javax.swing.JComboBox cb_search_product;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JPanel jPanel1;
    private javax.swing.JScrollPane jScrollPane2;
    public static javax.swing.JTable tbl_producto;
    private javax.swing.JTextField tf_search;
    // End of variables declaration//GEN-END:variables
}
